package com.zhu.storesmanager.views;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import com.zhu.storesmanager.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View;

/**
 * 拍照项界面
 */
public class PhotoView extends LinearLayout implements View.OnClickListener{

	private static final int PICK_FROM_CAMERA = 0;
    private static final int CROP_FROM_CAMERA = 1;

	private Activity mActivity = null;
	private Bitmap mBitmap = null; //保存的图片对象
	private Uri mImageCaptureUri = null;
	private ImageView mImagePreView = null;
	private boolean isImageChange = false;
	private boolean isTakingPhoto = false; //正在拍照

	public PhotoView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}
	
	public PhotoView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public PhotoView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		
	}

	/*
	 * (non-Javadoc)
	 * @see android.view.View#onFinishInflate()
	 */
	public void onFinishInflate(){
		findViewById(R.id.photodataitem_delete).setOnClickListener(this);
        findViewById(R.id.photodataitem_look).setOnClickListener(this);
        findViewById(R.id.photodataitem_take).setOnClickListener(this);
        mImagePreView = (ImageView)findViewById(R.id.photodataitem_preview);
	}

	/**
	 * 初始化数据
	 * @param activity
	 * @param titleId 标题ID
	 */
	public void initData(Activity activity, int titleId){
		mActivity = activity;
		((TextView)findViewById(R.id.photodataitem_title)).setText(titleId);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v != null){
			switch(v.getId()){
				case R.id.photodataitem_take: //拍照
					doTakePhotoAction();
					break;
				case R.id.photodataitem_delete: //删除
					deleteImage();
					break;
				case R.id.photodataitem_look: //查看
					showBigImage();
					break;
			}
		}
	}

	/**
	 * 设置标题名字
	 * @param text
	 */
	public void setLableText(String text){
		((TextView)findViewById(R.id.photodataitem_title)).setText(text);
	}
	/**
     * 处理照相
     */
    private void doTakePhotoAction() {
    	isTakingPhoto = true;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        try {
            intent.putExtra("return-data", true);
            mActivity.startActivityForResult(intent, PICK_FROM_CAMERA);
        } catch (ActivityNotFoundException e) {
            // Do nothing for now
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (resultCode != Activity.RESULT_OK) {
    		isTakingPhoto = false;
    		return;
    	}
        switch (requestCode) {
            case CROP_FROM_CAMERA:
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    if(mBitmap != null && !mBitmap.isRecycled()){
                         mBitmap.recycle();
                    }
                    Bitmap tem = extras.getParcelable("data");
                    mBitmap = makeTextBitMap(tem);
                    mImagePreView.setImageBitmap(mBitmap);
                    setImageChange(true);
                }
                File f = new File(mImageCaptureUri.getPath());
                if (f.exists()) {
                    f.delete();
                }
                isTakingPhoto = false;
                break;
            case PICK_FROM_CAMERA: //切图
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");
                intent.putExtra("outputX", 320);
                intent.putExtra("outputY", 240);
                intent.putExtra("return-data", true);
                mActivity.startActivityForResult(intent, CROP_FROM_CAMERA);
                break;
        }
    }

    /**
     * 图片加水印
     * @param bitmap 原图
     */
    private Bitmap makeTextBitMap(Bitmap bitmap) {
//        Canvas canvasTemp = new Canvas(bitmap);
//        canvasTemp.drawColor(Color.TRANSPARENT);
//        Paint p = new Paint();
//        p.setColor(Color.RED);
//        p.setAntiAlias(true);
//        p.setTextSize(22);
//        canvasTemp.drawText(Util.mVerifyUserResult.name, 0, 170, p);
//        canvasTemp.drawText(Util.getFormatTime(), 0, 200, p);
        return bitmap;
    }

    /**
     * 是否需要保存数据
     */
    public boolean isNeedSavedData(){
    	return isImageChange;
    }

    /**
     * 设置图片是否更改
     * @param isChanged 是否更改
     */
    public void setImageChange(boolean isChanged){
    	isImageChange = isChanged;
    }

    /**
     * 显示大图
     */
    private void showBigImage(){
        if(mBitmap != null){
            ImageView view = new ImageView(getContext());
            view.setImageBitmap(mBitmap);
            view.setScaleType(ScaleType.FIT_XY);
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setView(view);
            builder.create().show();
        }
    }

    /**
     * 获取保存的图片数据
     */
    public byte[] getBitmapData() {
    	if(mBitmap != null){
    		 int size = mBitmap.getWidth() * mBitmap.getHeight() * 4;
    	        ByteArrayOutputStream out = new ByteArrayOutputStream(size);
    	        try {
    	        	mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    	            out.flush();
    	            out.close();
    	            return out.toByteArray();
    	        } catch (IOException e) {
    	            return null;
    	        }
    	}
    	return null;
    }

    /**
     * 设置图片数据
     * @param data 图片数据
     */
    public void setImageData(byte[] data){
    	if(data != null && data.length > 0){
    		mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    		mImagePreView.setImageBitmap(mBitmap);
    	}else{
    		mImagePreView.setImageResource(R.drawable.photo_preview);
    	}
    }

    /**
     * 设置图片数据
     * @param bitmap 图片
     */
    public void setImageData(Bitmap bitmap){
    	if(bitmap != null){
    		mBitmap = bitmap;
    		mImagePreView.setImageBitmap(mBitmap);
    	}else{
    		mImagePreView.setImageResource(R.drawable.photo_preview);
    	}
    }

    /**
     * 删除图片
     */
    private void deleteImage(){
    	if(mBitmap != null){
    		setImageChange(true);
       	 	mImagePreView.setImageResource(R.drawable.photo_preview);
       	 	if(!mBitmap.isRecycled()){
       	 		mBitmap.recycle();
       	 	}
       	 	mBitmap = null;
    	}
    }

    /**
     * 是否正在拍照
     */
    public boolean isTakePhoto(){
    	return isTakingPhoto;
    }
}
